package com.uenpay.im.ui.old.activity.area;

import android.text.TextUtils;

import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.HttpInvokeResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class GetAreaInvokeItem extends HttpInvokeItem {

	public class GetAreaInvokeItemResult extends HttpInvokeResult {
		public ArrayList<AreaEntity> areaEntities = new ArrayList<AreaEntity>();
	}

	public GetAreaInvokeItemResult getOutput() {
		return (GetAreaInvokeItemResult) GetResultObject();
	}

	public GetAreaInvokeItem(String level, String parea) {
		String url = "";
		if (!TextUtils.isEmpty(parea)) {
			url = APIConfiguration.getBaseUrl() + "Communal/AreaCN/areaSample?level=" + level
					+ "&parea=" + parea + "&"
					+ APIConfiguration.getCustIdAndToken();
		} else {
			url = APIConfiguration.getBaseUrl() + "Communal/AreaCN/areaSample?level=" + level
					+ "&" + APIConfiguration.getCustIdAndToken();
		}

		SetUrl(url);
	}


	@Override
	protected Object DeserializeResult(String responseBody) {
		GetAreaInvokeItemResult result = new GetAreaInvokeItemResult();
		JSONObject json = null;
		try {
			json = new JSONObject(responseBody);
			result.status = json.optInt("status");
			result.msg = json.optString("msg");
		} catch (JSONException e) {
			e.printStackTrace();
			return result;
		}
		JSONArray arr = json.optJSONArray("data");
		for (int i = 0, size = arr.length(); i < size; i++) {
			result.areaEntities.add(desAreaEtity(arr.optJSONObject(i)));
		}
		return result;
	}

	private AreaEntity desAreaEtity(JSONObject json) {
		return new AreaEntity(json.optString("text"), json.optInt("isleaf"));
	}
}
